package com.zrrd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrrd.reggie.bean.Category;
import com.zrrd.reggie.bean.Dish;
import com.zrrd.reggie.bean.DishFlavor;
import com.zrrd.reggie.bean.dto.DishDto;
import com.zrrd.reggie.service.CategoryService;
import com.zrrd.reggie.service.DishFlavorService;
import com.zrrd.reggie.service.DishService;
import com.zrrd.reggie.util.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("sort");
        if (name != null && !name.equals("")) {
            wrapper.like("name", name);
        }
        dishService.page(pageInfo, wrapper);

        //BeanUtils.copyProperties 会复制 Page 对象中除 records 外的所有公共属性，包括：
        //total：总记录数,current：当前页码,size：每页大小,orders：排序条件,其他分页相关元数据
        Page<DishDto> dtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");

        List<Dish> dishList = pageInfo.getRecords();
        List<DishDto> dtoList = new ArrayList<>();
        for (Dish dish : dishList) {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(dish, dto);
            Category category = categoryService.getById(dish.getCategoryId());
            if (category != null) {
                dto.setCategoryName(category.getName());
            }
            dtoList.add(dto);
        }
        dtoPage.setRecords(dtoList);
        return R.sucess(dtoPage);
    }

    @PostMapping
    @CacheEvict(value="dishCache",allEntries = true)
    public R<String> saveDish(@RequestBody DishDto dto) {
        dishService.saveDish(dto);
        return R.sucess("增加菜品成功");
    }

    @GetMapping("/{id}")
    public R<DishDto> getDishWithFlavors(@PathVariable("id") Long id) {
        return R.sucess(dishService.getDishWithFlavors(id));
    }

    @PutMapping
    @CacheEvict(value="dishCache",allEntries = true)
    public R<String> updateDishWithFlavors(@RequestBody DishDto dto) {
        dishService.updateDishWithFlavors(dto);
        return R.sucess("修改菜品成功");
    }

    @CacheEvict(value="dishCache",allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") Integer status, Long[] ids) {
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        /*
        List<Dish> dishList=new ArrayList<>();
        for(Long id:ids){
            Dish dish=new Dish();
            dish.setId(id);
            dish.setStatus(status);
            dishList.add(dish);
        }
        dishService.updateBatchById(dishList);
         */
        return R.sucess("修改成功");
    }

    @CacheEvict(value="dishCache",allEntries = true)
    @DeleteMapping
    public R<String> deleteDish(Long[] ids) {
        return dishService.removeByIds(Arrays.asList(ids)) ? R.sucess("删除成功") : R.error("删除失败");
    }
    @Cacheable(value = "dishCache",key="#dish.categoryId+'_'+#dish.status")
    @GetMapping("/list")
    public R<List> list(Dish dish) {
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", dish.getCategoryId()).eq("status", 1).orderByDesc("sort");
        List<Dish> dishlist = dishService.list(wrapper);
        List<Dish> dtoList = new ArrayList<>();
        for (Dish d : dishlist) {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(d, dto);
            QueryWrapper<DishFlavor> flavorQueryWrapper = new QueryWrapper<>();
            flavorQueryWrapper.eq("dish_id", dish.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(flavorQueryWrapper);
            dto.setFlavors(flavorList);
            dtoList.add(dto);
        }
        return R.sucess(dtoList);
    }
}
